package com.dxf.hchat.service.impl;

import com.dxf.hchat.mapper.TbFriendMapper;
import com.dxf.hchat.mapper.TbFriendReqMapper;
import com.dxf.hchat.mapper.TbUserMapper;
import com.dxf.hchat.pojo.*;
import com.dxf.hchat.pojo.vo.Result;
import com.dxf.hchat.pojo.vo.User;
import com.dxf.hchat.service.UserService;
import com.dxf.hchat.utils.FastDFSClient;
import com.dxf.hchat.utils.IdWorker;
import com.dxf.hchat.utils.QRCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.digester.Digester;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private Environment environment;

    @Autowired
    private QRCodeUtils qrCodeUtils;

    @Autowired
    private TbFriendMapper tbFriendMapper;
    @Autowired
    private TbFriendReqMapper tbFriendReqMapper;


    @Override
    public List<TbUser> findAll() {
        List<TbUser> tbUsers = tbUserMapper.selectByExample(null);

        return tbUsers;
    }


    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    public User login(String username, String password) {

        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<TbUser> users = tbUserMapper.selectByExample(example);

        if (users != null && users.size() > 0) {

            //密码加密
            String encodingPassowrd = DigestUtils.md5DigestAsHex(password.getBytes());

            if (encodingPassowrd.equals(users.get(0).getPassword())) {
                //登录成功,返回user
                User user = new User();
                BeanUtils.copyProperties(users.get(0), user);

                return user;
            }
        }
        return null;
    }

    /**
     * 注册
     *
     * @param tbUser
     * @return
     */
    @Override
    public Result register(TbUser tbUser) {


        try {
            TbUserExample example = new TbUserExample();
            TbUserExample.Criteria criteria = example.createCriteria();
            criteria.andUsernameEqualTo(tbUser.getUsername());
            List<TbUser> userList = tbUserMapper.selectByExample(example);
            if (userList == null || userList.size() == 0) {
                tbUser.setId(idWorker.nextId());
                tbUser.setPicSmall("");
                tbUser.setNickname(tbUser.getUsername());
                tbUser.setCreatetime(new Date());
                //生成二维码
                //1 生成路径
                String tempDir = environment.getProperty("hcat.tmpdir");//保存的文件夹
                String tempDirFilePath=tempDir+"/"+tbUser.getUsername()+".png";
                //2 内容
                String qrcodeStr = "hichat://" + tbUser.getUsername();
                qrCodeUtils.createQRCode(tempDirFilePath,qrcodeStr);

                //fastDfs上传文件,并保存返回的url
                String url = fastDFSClient.uploadFile(new File(tempDirFilePath));
                String property = environment.getProperty("fdfs.httpurl");
                tbUser.setQrcode(property+url);
                tbUser.setPassword(DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes()));
                //注册
                int count = tbUserMapper.insert(tbUser);
                if (count > 0) {
                    return new Result(true, "注册成功");
                }

            }

            return new Result(false, "注册失败");
        } catch (Exception e) {
            return new Result(false, "注册失败");
        }
    }

    /**
     * 上传文件
     *
     * @param file
     * @param userId
     * @return
     */
    @Override
    public User upload(MultipartFile file, String userId) {

        try {
            //返回在fastDfs中的url,这个路径不带http://192.168.25.133/
            String url = fastDFSClient.uploadFace(file);
            //在fastDfs上传的时候会自动生成一个缩略图
            //缩略图的文件名是 : 文件名_150×150.后缀
            String[] fileNameList = url.split("\\.");
            String fileName = fileNameList[0];
            String ext = fileNameList[1];

            String picSmallUrl = fileName + "_150x150." + ext;

            TbUser tbUser = tbUserMapper.selectByPrimaryKey(userId);

            String property = environment.getProperty("fdfs.httpurl");

            tbUser.setPicSmall(property + picSmallUrl);//设置小图片

            tbUser.setPicNormal(property + url);//设置大图片
            tbUserMapper.updateByPrimaryKey(tbUser);

            User user = new User();

            BeanUtils.copyProperties(tbUser, user);

            return user;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 修改昵称
     *
     * @param id
     * @param nickname
     * @return
     */
    public User updateNickname(String id, String nickname) {

        if (!StringUtils.isNoneEmpty(nickname)) {
            throw new RuntimeException("昵称不能为空");
        }


        try {
            TbUser tbUser = tbUserMapper.selectByPrimaryKey(id);
            if (tbUser != null) {
                tbUser.setNickname(nickname);

                tbUserMapper.updateByPrimaryKey(tbUser);
                User user = new User();

                BeanUtils.copyProperties(tbUser, user);
                return user;

            }
        } catch (BeansException e) {
            return null;
        }

        return null;
    }

    /**
     * 根据userId获取user对象
     *
     * @param userId
     * @return
     */
    public User findById(String userId) {

        TbUser tbUser = null;
        try {
            tbUser = tbUserMapper.selectByPrimaryKey(userId);
            User user = new User();

            BeanUtils.copyProperties(tbUser, user);
            return user;
        } catch (BeansException e) {
            return null;
        }


    }

    /**
     * 根据朋友的用户名和自己的userId查询朋友
     * @param userId 自己的userId
     * @param friendUsername 朋友名
     * @return
     */
    @Override
    public User findByUsername(String userId, String friendUsername) {

        //1 不能自己添加自己为好友
        TbUserExample example=new TbUserExample();
        TbUserExample.Criteria friendExampleCriteria = example.createCriteria();
        friendExampleCriteria.andUsernameEqualTo(friendUsername);

        List<TbUser> friendList = tbUserMapper.selectByExample(example);

        User user = new User();

        BeanUtils.copyProperties(friendList.get(0),user);

        return user;
    }






}
